<template>
	<view>
		<u-gap height="15px" />
		<view class="dm-box ">
			<view class="tn-text-bold tn-text-lg tn-margin tn-flex tn-flex-row-center">精彩短剧 上{{Config.appName}}</view>
			<view class="dm-horizontal-line-xl--grey" />

			<view class="tn-flex tn-flex-row-center dm-main-text-color">邀请好友奖金豆，好友消费或佣金</view>

			<view class="tn-flex tn-flex-direction-column ">
				<view class="tn-flex tn-flex-row-center">
					<l-painter css="width: 160px; height: 160px;" ref="painter1" performance>
						<l-painter-view css="padding:5px;position:absolute;">
							<l-painter-qrcode
								css="background:#fff;width: 130px; height: 130px;padding:10px;border-radius: 10rpx;"
								:text="inviteUrl" />
						</l-painter-view>
					</l-painter>
				</view>
				<view class="tn-flex tn-flex-row-center tn-text-sm dm-color-wechat"> 微信扫一扫立即追剧</view>
			</view>

			<view class="tn-flex tn-flex-row-between tn-text-bold">
				<view class="tn-flex">邀请码</view>
				<view class="tn-flex tn-bg-gray dm-padding-left-right">{{inviteCode}}</view>
				<view class="tn-flex tn-text-sm dm-color-wechat" @click="copyText(inviteCode)">复制</view>
			</view>
		</view>

		<view class="tn-flex tn-flex-row-between tn-margin-xl">
			<view style="width: 100px">
				<u-button v-if="isWeChat" :custom-style="{background:'#11AE14',color:'#FFF',border:'0px'}" openType="share"
					shape="circle">分享推广码</u-button>
			</view>
			<view style="width: 100px">
				<u-button v-if="isWeChat" :custom-style="{background:'#11AE14',color:'#FFF',border:'0px'}" shape="circle"
					@click="savePoster">下载推广码</u-button>
			</view>
		</view>

		<view hidden="true">
			<l-painter css="width: 300px; height: 390px;" @success="path = $event" ref="painter" performance>
				<l-painter-image
					src="https://6c61-laien-shortplay-5gva73vg5dc4740e-1325485076.tcb.qcloud.la/2024/04/29/57351246-29813867-inviteposterbg.png"
					css="object-fit: contain; width: 300px; height: 390px;" />
				<l-painter-view css="position:absolute;bottom:67px;left:130px">
					<l-painter-text css="display: block; font-size: 28rpx; fontWeight: bold" :text="inviteCode" />
				</l-painter-view>
				<l-painter-view css="padding:5px;position:absolute;bottom:120px;left:85px">
					<l-painter-qrcode
						css="background:#fff;width: 100px; height: 100px;padding:10px;border-radius: 10rpx;"
						:text="inviteUrl" />
				</l-painter-view>
			</l-painter>
		</view>

		<banner-ad :config="adConfig.wx_banner_myInviteCode" />

	</view>
</template>

<script>
	import common_mixin from '@/libs/mixin/common_mixin.js'
	import BannerAd from "@/components/banner-ad/banner-ad.vue";
	import Config from "../../utils/config";
	import {
		getShareUrl
	} from "../../api/api";

	export default {
		computed: {
			Config() {
				return Config
			}
		},
		components: {
			BannerAd
		},
		mixins: [common_mixin],
		name: "to_invite",
		data() {
			return {
				inviteCode: "",
				inviteUrl: '',
				genImg: '',
				isWeChat:true
			}
		},
		onLoad() {
			this.isWeChat = Config.isWeChat;
		},
		onShow() {
			this.inviteCode = this.vuex_user.my_invite_code
			this.getShareUrl()
		},
		methods: {
			async getShareUrl() {
				let data = await this.$api.getShareUrl({
					isH5:!this.isWeChat
				});
				console.log(data)
				this.inviteUrl = data.url_link 
			},
			savePoster() {
				this.$refs.painter.canvasToTempFilePathSync({
					fileType: "jpg",
					// pathType: 'url',
					quality: 1,
					success: (res) => {
						console.log(res.tempFilePath);
						this.genImg = res.tempFilePath
						this.saveImage()
					},
				});
			},
			saveImage() {
				let imageUrl = this.genImg

				// #ifdef H5
				uni.downloadFile({
					url: imageUrl,
					success: (res) => {
						console.log("saveImage:" + res.tempFilePath)
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: res1 => {
									console.log("success")
									this.$u.toast("成功" + res1)
								},
								fail: err1 => {
									console.log("error")
									this.$u.toast("失败" + err1)
								},
								complete: () => {
									this.$u.toast("保存到相册")
								}
							});

							/* 可以在电脑浏览器下载，移动端iOS不行，安卓微信浏览器不行，安卓外部浏览器可以 */
							this.tempFilePath = res.tempFilePath;
							const aEle = document.createElement('a');
							aEle.download = '邀请海报'; // 设置下载的文件名，默认是'下载'
							aEle.href = res.tempFilePath;
							document.body.appendChild(aEle);
							aEle.click();
							aEle.remove(); // 下载之后把创建的元素删除
						} else {
							this.$u.toast("下载图片失败")
						}
					},
					fail: (error) => {
						this.$u.toast('下载图片失败：', error);
					},
				});
				// #endif

				// #ifdef MP-WEIXIN
				this.saveAlbum();
				// #endif

			},
			saveAlbum() {
				uni.getSetting({
					//获取用户的当前设置
					success: (res) => {
						if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
							this.saveImageToPhotosAlbum();
						} else {
							uni.authorize({ //如果没有授权，向用户发起请求
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.saveImageToPhotosAlbum();
								},
								fail: () => {
									uni.showToast({
										title: "请打开保存相册权限，再点击保存相册分享",
										icon: "none",
										duration: 3000
									});
									setTimeout(() => {
										uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
											success: (res2) => {
												console.log(res2.authSetting)
											}
										});
									}, 3000);
								}
							})
						}
					}
				})
			},
			saveImageToPhotosAlbum() {
				let base64 = this.genImg.replace(/^data:image\/\w+;base64,/, "");
				//去掉data:image/png;base64,
				let filePath = wx.env.USER_DATA_PATH + '/qrcode.png';
				uni.getFileSystemManager().writeFile({
					filePath: filePath,
					//创建一个临时文件名
					data: base64,
					//写入的文本或二进制数据
					encoding: 'base64',
					// 写入当前文件的字符编码
					success: res => {
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: function(res2) {
								uni.showToast({
									title: '保存成功，请从相册选择再分享',
									icon: "none",
									duration: 5000
								})
							},
							fail: function(err) {
								console.log(err.errMsg);
							}
						})
					},
					fail: err => {
						console.log(err)
					}
				})
			},

			onShareAppMessage(res) {
				console.log('分享', res);
				return {
					title: '', // 默认为小程序名称
					path: '/pages/index/index?invite_code=' + this.vuex_user.my_invite_code,
					imageUrl: '', // 默认为当前页面的截图
					success: (res) => {
						// 转发成功
						console.log('转发成功:', res);
					},
					fail: function(res) {
						console.log('转发失败:', res);
					},
				}
			},
		}
	}
</script>

<style scoped lang="scss">

</style>